package com.smarttest.common.util.protocol;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.smarttest.common.beans.protolcol.LiquidLevel;

/**
 * 超声波液位计消息
 *
 */
public class LiquidometerMessage {

	private static Logger LOG = LoggerFactory.getLogger(LiquidometerMessage.class);
	
	// *XD
	public static final int[] DELIMITER_H = new int[] { 0x2A, 0x58, 0x44 };
	// #
	public static final int[] DELIMITER_T = new int[] { 0x23 };

	public static int minMsgLength;
	
	private int itemCount = 8;
	
	private int hasCheckBitCount = 9;

	private String imei;
	private byte[] data;

	private List<LiquidLevel> dataList = null;

	public List<LiquidLevel> getDataList() {
		if(dataList == null || dataList.isEmpty()){
			String txt = new String(data);
			int len = txt.length();
			
			dataList = new ArrayList<LiquidLevel>();
			if(txt.charAt(0) == '*' && txt.charAt(len - 1) == '#') {
				String[] rows = txt.split("#");
				
				LiquidLevel liquidLevel = null;
				boolean isMainTank = true;
				for(int n=0; n<rows.length; n++) {
					String row = rows[n];
					String[] items = row.split(",");
					int count = items.length;
					if(!(count == itemCount||count == hasCheckBitCount)){
						LOG.error("Invalid data format: ", row);
						continue;
					}
					if (count == hasCheckBitCount) {
						byte [] datatemp=row.getBytes();
						byte flag = datatemp[0];
						for (int j = 1, c = datatemp.length - 3; j < c; j++)
							flag ^= datatemp[j];
						
						//计算获得的校验值 result
						String result = Integer.toHexString(flag & 0xFF);
						if (result.length() == 1) {
							result = '0' + result;
						}
						//原始的校验值 checkbit
						String checkbit=null;
						if (items[8] != null && items.length > 2) {
                             checkbit = items[8].substring(0, 2);
						} else {
							LOG.error("超声波液位计 无效校验位："
									+ Hex.encodeHexString(datatemp));
							continue;
						}
						// 校验位无效
						if (result!=null && !result.equals(checkbit)) {

							if (LOG.isWarnEnabled())
								LOG.error("超声波液位计 无效校验位："
										+ Hex.encodeHexString(datatemp));
							continue;
						}
					}					
					
					try {
						 if("*XD2".equals(items[0])) {//副油箱
							if(liquidLevel == null) {
								if (LOG.isWarnEnabled())
									LOG.error("超声波液位计 没有主油箱数据，直接上报了副油箱数据：" + row);
								continue;
							}
							isMainTank = false;
							
							// 协议, 软/硬件版本号, 安装状态&软件版本							
							liquidLevel.setSubVersion(items[1]); 
							
							//标识位
							liquidLevel.setSubSign(items[2]);
							
							// 液位值
							double ll = Double.parseDouble(items[3]);
							liquidLevel.setSubLevel(ll/100);
							
							// 信号强度, 软件状态代码, 硬件故障代码
							String signal = items[4];
							liquidLevel.setSubSignalIntensity(Integer.parseInt(signal.substring(0, 2), 16)); 
							liquidLevel.setSubSoftwareStatus(Integer.parseInt(signal.substring(2, 3), 36));
							liquidLevel.setSubHardwareStatus(Integer.parseInt(signal.substring(3,4), 16));
							
							//标识值
							liquidLevel.setSubSignValue(items[5]);							
							
							//实时液位值
							double rll = Double.parseDouble(items[6]);
							liquidLevel.setRealSubLevel(rll/100);
							
							//温度
							String temperature = items[7];
							if(temperature != null && !temperature.equals("null")) {
								liquidLevel.setSubTemperature(Double.parseDouble(temperature));
							}
						} else {//主油箱
							isMainTank = true;
							liquidLevel = new LiquidLevel();
							
							liquidLevel.setImei(imei);
							
							// 协议, 软/硬件版本号, 安装状态&软件版本							
							liquidLevel.setVersion(items[1]); 
							
							//标识位
							liquidLevel.setSign(items[2]);
							
							//液位输出值（单位 0.1mm，11.32cm）
							double ll = Double.parseDouble(items[3]);
							liquidLevel.setMainLevel(ll/100);
							
							// 信号强度, 软件状态代码, 硬件故障代码
							String signal = items[4];
							liquidLevel.setSignalIntensity(Integer.parseInt(signal.substring(0, 2), 16)); 
							liquidLevel.setSoftwareStatus(Integer.parseInt(signal.substring(2, 3), 36));
							liquidLevel.setHardwareStatus(Integer.parseInt(signal.substring(3,4), 16));
							
							//标识值
							liquidLevel.setSignValue(items[5]);
							
							//实时液位值
							double rll = Double.parseDouble(items[6]);
							liquidLevel.setRealMainLevel(rll/100);
							
							//温度
							String temperature = items[7];
							if(temperature != null && !temperature.equals("null")) {
								liquidLevel.setTemperature(Double.parseDouble(temperature));
							}
						}
					} catch (Exception e) {
						LOG.error("Parse liquid level error: {}", row, e);
					}
					
					//判断当前解析是不是副油箱， 如果是副油箱，将当前对象设为空，用于判断如果下次还是副油箱的处理逻辑
					if(!isMainTank) {
						liquidLevel = null;
					} else {
						dataList.add(liquidLevel);
					}
				}
			}
		}
		return dataList;
	}

	public String getImei() {
		return imei;
	}

	public void setImei(String imei) {
		this.imei = imei;
	}

	public byte[] getData() {
		return data;
	}

	public void setData(byte[] data) {
		this.data = data;
	}
}
